﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mystery.SharePoint
{
	/// <summary>
	/// Extension methods for HashTable
	/// </summary>
	public static class HashTableExtension
	{
		/// <summary>
		/// Writes a value to the hash table
		/// </summary>
		/// <param name="ht"></param>
		/// <param name="key">The key</param>
		/// <param name="value">The value</param>
		/// <returns>True if the hashtable was updated, otherwise false</returns>
		public static bool Write(this Hashtable ht, string key, object value)
		{
			if (ht == null) throw new ArgumentNullException("ht");

			// checking an existing value
			if (ht.ContainsKey(key) == true)
			{
				// no value specified, so we remove it
				if (value == null)
				{
					ht.Remove(key);
					return true;
				}
				//compare against existing value
				object current = ht[key];
				if (current.Equals(value) == false)
				{
					ht[key] = value;
					return true;
				}
			}
			else // value doesn't exist
			{
				if (value != null)
				{
					ht.Add(key, value);
					return true;
				}
			}
			return false;
		}

		/// <summary>
		/// Reads a value from the hash table
		/// </summary>
		/// <param name="ht"></param>
		/// <param name="key">The key of the value we are looking for</param>
		/// <param name="defaultValue">A value to use if the key doesn't exist in the hash table</param>
		/// <returns>The value stored in the hash table or the default value</returns>
		public static T Read<T>(this Hashtable ht, string key, T defaultValue)
		{
			if (ht == null) throw new ArgumentNullException("ht");

			// the property exists so we can return the actual value
			if (ht.ContainsKey(key) == true)
			{
				return (T)ht[key];
			}
			// property does not exists so we return a default value
			return defaultValue;
		}
	}
}
